<template>
	<view>
		<view class="main">
			<view class="steps-main">
				<up-steps :current="currentStep">
					<up-steps-item title="连接蓝牙" :desc="bluetoothDesc">
					</up-steps-item>
					<up-steps-item title="连接wifi" desc="" ></up-steps-item>
					<up-steps-item title="完成添加" desc=""></up-steps-item>
				</up-steps>
			</view>
			<view class="content">
				<view class="content-bluetooth" v-show="currentStep == 0">
					<view class="">
						<up-loading-icon textSize="18"></up-loading-icon>
					</view>
					<view class="">
						<up-text type="primary" text="蓝牙连接中,请稍后..."></up-text>
					</view>
				</view>
				<view class="content-wifi" v-show="currentStep == 1">
					<up-text text="输入WI-FI密码"></up-text>
					<up-text text="提示: 不支持5G WI-FI"></up-text>
					<view>
						<up-picker 
							:show="show" 
							:columns="wifiList" 
							@cancel="cancelWifiList"
							@confirm="confirmWifiList"
						>
						</up-picker>
						WI-FI: {{currentWifi}}
						<up-button @click="chooseWifi">选择WI-FI</up-button>
						<up-input
							placeholder="请输入密码"
							border="surround"
							type="password"
							prefixIcon="lock"
							v-model="wifiPwd"
						></up-input>
						<up-button @click="connectWifi">连接</up-button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { ref, reactive } from 'vue';
import { onMounted } from 'vue';

let currentStep = ref(0)
let bluetoothDesc = ref('正在连接...')
let currentWifi = ref('')
let wifiPwd = ref('')

let bluetoothService = reactive({
	deviceId: '',
	// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
	serviceId: '',
	// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
	characteristicId: '',
})
onMounted(() => {
	
})
onLoad((option) => {
	console.log(option.deviceId); //打印出上个页面传递的参数。
	console.log(); //打印出上个页面传递的参数。
	uni.setNavigationBarTitle({
		title: option.name
	})
	
	// 连接BLE蓝牙
	connectBleBT(option)
})

let show = ref(false);
let wifiList = reactive([
	[]
]);
const connectWifi = () => {
	console.log(currentWifi.value, wifiPwd.value)
	
	// 向蓝牙设备发送一个0x00的16进制数据
	// let msg = `wifi:${currentWifi.value},${wifiPwd.value },111111111111111111111111111333333333333111111111111111`
	// let msg = 'eyJjbWQiOndpZmlfY29uZmlnLCJkYXRhIjp7InNzaWQiOjExMSwicHdkIjoyMjJ9fQ=='
	
	let msg = {
		cmd: 1, // 1 --> ‘wifi_config’
		data: {
			ssid: currentWifi.value,
			pwd: wifiPwd.value
		}
	}
	// let msg = `{"cmd":wifi_config,"data":{"ssid":${currentWifi.value},"pwd":${wifiPwd.value}}}`
	msg = JSON.stringify(msg)
	
	msg = btoa(msg);
	
	const buffer = new ArrayBuffer(msg.length)
	const dataView = new DataView(buffer)
	dataView.setUint8(0, 0)
	
	for (var i = 0; i < msg.length; i++) {
		dataView.setUint8(i, msg.charAt(i).charCodeAt())
	}
	console.log(buffer)
	console.log(bluetoothService)
	uni.writeBLECharacteristicValue({
	  // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
	  deviceId: bluetoothService.deviceId,
	  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
	  serviceId: bluetoothService.serviceId,
	  // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
	  characteristicId: bluetoothService.characteristicId,
	  // 这里的value是ArrayBuffer类型
	  value: buffer,
		writeType: 'writeNoResponse',
	  success(res) {
	    console.log('writeBLECharacteristicValue success', res.errMsg)
	  },
		fail(e){
			console.log("write fail: ", e)
		}
	})
}
const chooseWifi = () => {
	wifiList[0] = []
	// 主窗体  
	var MainActivity = plus.android.runtimeMainActivity()  
	// 上下文  
	var Context = plus.android.importClass('android.content.Context')  
	// 导入WIFI管理 和 WIFI 信息 的class  
	plus.android.importClass("android.net.wifi.WifiManager")  
	plus.android.importClass("android.net.wifi.WifiInfo")  
	plus.android.importClass("android.net.wifi.ScanResult")  
	plus.android.importClass("java.util.ArrayList")  
	// 获取 WIFI 管理实例  
	var wifiManager = MainActivity.getSystemService(Context.WIFI_SERVICE)  

	// 获取当前连接WIFI的信息  
	//var info = wifiManager.getConnectionInfo()  
	// 获取当前 WIFI 连接的 SSID (WIFI 名称)  
	//var ssid = info.getSSID()  
	// 这里的 获取到的名称 是 带 双引号的 如 "cmcc"    
	// 所以我们这里处理一下  
	//ssid = ssid.replace(/(^\"*)|(\"*$)/g, "")  

	var resultList = wifiManager.getScanResults(),  
			len = resultList.size()  

	for(var i = 0; i < len; i++) {  
		console.log(resultList.get(i).plusGetAttribute('SSID'))
		const ssid = resultList.get(i).plusGetAttribute('SSID')
		if(ssid) {
			wifiList[0].push(ssid)
		}
	}
	show.value=true
	console.log(wifiList)
}

const cancelWifiList = (e) => {
	show.value = false
}

const confirmWifiList = (e) => {
	console.log(e)
	currentWifi.value = e.value[0]
	cancelWifiList()
}
const connectBleBT = (v) => {

	uni.createBLEConnection({
	  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
	  deviceId: v.deviceId,
	  success(res) {
	    console.log(res)
			setTimeout(() => {
				getBLEDeviceServices(v.deviceId);
			}, 1500)
	  }
	})
	uni.onBLEConnectionStateChange((res) => {
		const deviceId = res.deviceId;
		const connected = res.connected;
	
		if (connected) {
			console.log(`设备(${deviceId})连接状态变为：已连接`);
		} else {
			console.log(`设备(${deviceId})连接状态变为：已断开`);
			// 可在此处处理断开连接后的逻辑，如重连、通知用户等
		}
	});
	
	async function getBLEDeviceServices(deviceId) {
	  try {
	    const services = await uni.getBLEDeviceServices({
	      deviceId: deviceId,
	    });
	
	    console.log(`设备(${deviceId})提供的服务：`, services);
			
			// buff 转 str 
				function arrayBufferToString(buffer) {
			    let x = new Uint8Array(buffer);
			    // log(x)
			    let strHex = ""
			    let str = ""
			    for (let i = 0; i < x.length; i++) {
			      strHex = strHex + x[i].toString(16).padStart(2, "0")
			      str = str + String.fromCharCode(x[i])
			    }
					return strHex;
				}
				// str 转 buff
				function str2ab(str) {
					const buffer = new ArrayBuffer(str.length / 2);
					let x = new Uint8Array(buffer);
					for (let i = 0; i < x.length; i++) {
					    x[i] = parseInt(str.substr(2 * i, 2), 16)
					}
					return buffer;
				}
				
			
			uni.getBLEDeviceCharacteristics({
			  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			  deviceId,
			  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
			  serviceId: services.services[2].uuid,
			  success(res) {
			    console.log('device getBLEDeviceCharacteristics:', res.characteristics)
					
					// 向蓝牙设备发送一个0x00的16进制数据
					let msg = 'hello'
					    
					const buffer = new ArrayBuffer(msg.length)
					const dataView = new DataView(buffer)
					// dataView.setUint8(0, 0)
					
					for (var i = 0; i < msg.length; i++) {
						dataView.setUint8(i, msg.charAt(i).charCodeAt())
					}
					console.log(buffer)
					
					bluetoothService = {
						deviceId,
						// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
						serviceId: services.services[2].uuid,
						// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
						characteristicId: res.characteristics[0].uuid,
					}
					
					uni.writeBLECharacteristicValue({
					  // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
					  deviceId,
					  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					  serviceId: services.services[2].uuid,
					  // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
					  characteristicId: res.characteristics[0].uuid,
					  // 这里的value是ArrayBuffer类型
					  value: buffer,
						writeType: 'writeNoResponse',
					  success(res) {
					    console.log('writeBLECharacteristicValue success', res.errMsg)
							bluetoothDesc.value = '已连接'
							currentStep.value = 1
							uni.setBLEMTU({
								deviceId,
								mtu: 128,
								success(e) {
									console.log(e)
								},
								fail(e) {
									console.log(e)
								}
							})
					  },
						fail(e){
							console.log("write fail: ", e)
						}
					})
			  }
			})
	    // 可在此处处理服务列表，如获取特征值、订阅通知等
	  } catch (error) {
	    console.error('获取蓝牙设备服务失败', error);
	  }
	}
}
</script>

<style scoped>
.main{
	display: flex;	
	flex-direction: column;
	height: calc(100vh - 44px);
}
.steps-main{
	background-color: #fff;
	border-radius: 10px;
	margin: 10px;
	padding: 10px 0px;
}
.content {
	margin: 0px 10px 10px 10px;
	background-color: #fff;
	flex-grow: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}
.content-bluetooth{
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}
</style>
